package com.chookss.home.knowledge;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.entity.FileEntity;
import com.chookss.home.entity.KnowledgeEntity;
import com.chookss.home.entity.KnowledgeTypeEntity;
import com.chookss.home.knowledge.adaper.JustOpenListAdapter;
import com.chookss.home.knowledge.adaper.MyDirectoryAdapter;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.LoadingDialog2;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.ImmersionFragment;
import com.liulishuo.okdownload.DownloadTask;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.annotations.Nullable;

@SuppressLint("ValidFragment")
public class KnowledgeBaseFragment extends ImmersionFragment {

    public Activity mContext;
    Unbinder unbinder;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.title_back)
    LinearLayout title_back;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvRight)
    TextView tvRight;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.rlTitle)
    RelativeLayout rlTitle;
    @BindView(R.id.rcvDirectory)
    RecyclerView rcvDirectory;
    @BindView(R.id.tvJust)
    TextView tvJust;
    @BindView(R.id.rcvJust)
    RecyclerView rcvJust;
    @BindView(R.id.rvType)
    RecyclerView rvType;
    @BindView(R.id.rlType)
    RelativeLayout rlType;

    private MyDirectoryAdapter directoryAdapter;
    private JustOpenListAdapter justOpenListAdapter;
    private TypeAdapter typeAdapter;
    private List<KnowledgeTypeEntity> typeEntityList = new ArrayList<>();
    private List<KnowledgeEntity> directoryList = new ArrayList<>();
    private List<FileEntity.ListBean> justList = new ArrayList<>();
    private int type = 0; //0一级页面没有返回1是activity要返回
    private String TAG = "KnowledgeBaseFragment_DownloadFile";
    private String resourceType = "";////        资源类型（1资料，2长视频，3短视频4新闻5图文 6图片）
    private String resourceName = "";////        资源类型（1资料，2长视频，3短视频 6图片）
    private LoadingDialog2 loadingDialog2;

    public KnowledgeBaseFragment() {
    }

    public KnowledgeBaseFragment(int type) {
        this.type = type;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_knowledge, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        //顶部状态栏 处理
        loadingDialog2 = new LoadingDialog2(mContext);
        NavigationTools.saveUseRecord(mContext, "1", "24");
        if (type == 0) {
            int statusBarHeight = Utils.getStatusBarHeight(mContext);
            RelativeLayout.LayoutParams topAllParams = (RelativeLayout.LayoutParams) statusBar.getLayoutParams();
            topAllParams.height = statusBarHeight;
            statusBar.setLayoutParams(topAllParams);
            RelativeLayout.LayoutParams rlTypeParams = (RelativeLayout.LayoutParams) rlType.getLayoutParams();
            rlTypeParams.setMargins(0, statusBarHeight + Utils.dip2px(mContext, (float) 50.5), 0, 0);
            rlType.setLayoutParams(rlTypeParams);
            statusBar.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            statusBar.setVisibility(View.VISIBLE);
            title_back.setVisibility(View.GONE);
            tvTitle.getPaint().setFakeBoldText(true);
        } else {
            statusBar.setVisibility(View.GONE);
            title_back.setVisibility(View.VISIBLE);
        }
        rcvDirectory.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        directoryAdapter = new MyDirectoryAdapter(R.layout.item_knowledge_directory, mContext, directoryList, 0, resourceType);
        rcvDirectory.setAdapter(directoryAdapter);
        rcvJust.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        justOpenListAdapter = new JustOpenListAdapter(R.layout.item_knowledge_look, mContext, justList, TAG);
        rcvJust.setAdapter(justOpenListAdapter);
        KnowledgeTypeEntity knowledgeTypeEntity = new KnowledgeTypeEntity();
        knowledgeTypeEntity.setSelect(false);
        knowledgeTypeEntity.setName("综合");
        knowledgeTypeEntity.setType("");
        typeEntityList.add(knowledgeTypeEntity);
        KnowledgeTypeEntity knowledgeTypeEntity2 = new KnowledgeTypeEntity();
        knowledgeTypeEntity2.setSelect(false);
        knowledgeTypeEntity2.setName("视频");
        knowledgeTypeEntity2.setType("2");
        typeEntityList.add(knowledgeTypeEntity2);
        KnowledgeTypeEntity knowledgeTypeEntity3 = new KnowledgeTypeEntity();
        knowledgeTypeEntity3.setSelect(false);
        knowledgeTypeEntity3.setName("小视频");
        knowledgeTypeEntity3.setType("3");
        typeEntityList.add(knowledgeTypeEntity3);
        KnowledgeTypeEntity knowledgeTypeEntity4 = new KnowledgeTypeEntity();
        knowledgeTypeEntity4.setSelect(false);
        knowledgeTypeEntity4.setName("资料");
        knowledgeTypeEntity4.setType("1");
        typeEntityList.add(knowledgeTypeEntity4);
        KnowledgeTypeEntity knowledgeTypeEntity5 = new KnowledgeTypeEntity();
        knowledgeTypeEntity5.setSelect(false);
        knowledgeTypeEntity5.setName("图文");
        knowledgeTypeEntity5.setType("5");
        typeEntityList.add(knowledgeTypeEntity5);
        KnowledgeTypeEntity knowledgeTypeEntity6 = new KnowledgeTypeEntity();
        knowledgeTypeEntity6.setSelect(false);
        knowledgeTypeEntity6.setName("图片");
        knowledgeTypeEntity6.setType("6");
        typeEntityList.add(knowledgeTypeEntity6);
        rvType.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rvType.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_gray)));
        typeAdapter = new TypeAdapter(R.layout.item_subject_choice, mContext, typeEntityList);
        rvType.setAdapter(typeAdapter);
        registerBoradcastReceiver();
    }

    @Override
    public void onLazyAfterView() {
        super.onLazyAfterView();
        getLatelyResourceList();
        directoryList.clear();
        directoryList.addAll(XJson.getKnowledgeEntity(mContext,KnowledgeEntity.class));
        directoryAdapter.notifyDataSetChanged();
    }

    @Override
    public void onVisible() {
        super.onVisible();
        getCatalogData();
    }

    private void getCatalogData() {
        resourceType = "";
        resourceName = "";
        if (typeEntityList.get(0).isSelect() || (typeEntityList.get(1).isSelect() && typeEntityList.get(2).isSelect() && typeEntityList.get(3).isSelect()&& typeEntityList.get(4).isSelect()&& typeEntityList.get(5).isSelect())) {
            resourceType = "1,2,3,5,6";
        } else if (!typeEntityList.get(1).isSelect() && !typeEntityList.get(2).isSelect() && !typeEntityList.get(3).isSelect() && !typeEntityList.get(4).isSelect()&& !typeEntityList.get(5).isSelect()) {
            resourceType = "";
        } else {
            for (int i = 0; i < typeEntityList.size(); i++) {
                if (i >= 1 && typeEntityList.get(i).isSelect()) {
                    if (Utils.isNull(resourceType)) {
                        resourceType = resourceType + typeEntityList.get(i).getType();
                        resourceName = resourceName + typeEntityList.get(i).getName();
                    } else {
                        resourceType = resourceType + "," + typeEntityList.get(i).getType();
                        resourceName = resourceName + "、" + typeEntityList.get(i).getName();
                    }
                }
            }
        }
        if (Utils.isNull(resourceType) || resourceType.equals("1,2,3,5,6")) {
            tvRight.setText("全部");
            tvRight.setTextColor(Color.parseColor("#333333"));
        } else {
            tvRight.setText(resourceName);
            tvRight.setTextColor(Color.parseColor("#333333"));
//            tvRight.setTextColor(mContext.getResources().getColor(R.color.main_color));
        }
        directoryAdapter.setResourceType(resourceType);
        Map<String, String> map = new HashMap<>();
        //        catalogType 目录类型 1-小视频，2长视频 3资料库4新闻5图文6图片
        if (!Utils.isNull(resourceType)) {
            if (resourceType.equals("1,2,3,5,6")) {
            } else {
                map.put("resourceType", resourceType);
            }
        }
        map.put("catalogType", "0");
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<KnowledgeEntity>>>() {
        }.getType(), null, Urls.selectCatalogTreeZsk, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<KnowledgeEntity>>() {
            @Override
            public void onSuccess(List<KnowledgeEntity> data) {
                if (data != null && data.size() > 0) {
                    XJson.setKnowledgeEntity(mContext,data);
                    directoryList.clear();
                    directoryList.addAll(data);
                    directoryAdapter.notifyDataSetChanged();
                }
                if (loadingDialog2 != null) {
                    loadingDialog2.dismiss();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
                if (loadingDialog2 != null) {
                    loadingDialog2.dismiss();
                }
            }
        });
    }

    private void getLatelyResourceList() {
        resourceType = "";
        if (typeEntityList.get(0).isSelect() || (typeEntityList.get(1).isSelect() && typeEntityList.get(2).isSelect() && typeEntityList.get(3).isSelect()&& typeEntityList.get(4).isSelect()&& typeEntityList.get(5).isSelect())) {
            resourceType = "1,2,3,5,6";
        } else if (!typeEntityList.get(1).isSelect() && !typeEntityList.get(2).isSelect() && !typeEntityList.get(3).isSelect() && !typeEntityList.get(4).isSelect()&& !typeEntityList.get(5).isSelect()) {
            resourceType = "";
        } else {
            for (int i = 0; i < typeEntityList.size(); i++) {
                if (i >= 1 && typeEntityList.get(i).isSelect()) {
                    if (Utils.isNull(resourceType)) {
                        resourceType = resourceType + typeEntityList.get(i).getType();
                    } else {
                        resourceType = resourceType + "," + typeEntityList.get(i).getType();
                    }
                }
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", "1");
        map.put("pageSize", "20");
        map.put("type", "0");
        if (!Utils.isNull(resourceType)) {
            if (resourceType.equals("1,2,3,5,6")) {
            } else {
                map.put("resourceType", resourceType);
            }
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<FileEntity.ListBean>>>() {
        }.getType(), null, Urls.getLatelyResourceList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<FileEntity.ListBean>>() {
            @Override
            public void onSuccess(List<FileEntity.ListBean> data) {
                if (data != null && data.size() > 0) {
                    justList.clear();
                    justList.addAll(data);
                    justOpenListAdapter.notifyDataSetChanged();
                    rcvJust.setVisibility(View.VISIBLE);
                    tvJust.setVisibility(View.VISIBLE);
                } else {
                    if (justList.size() == 0) {
                        rcvJust.setVisibility(View.GONE);
                        tvJust.setVisibility(View.GONE);
                    }
                }
                if (loadingDialog2 != null) {
                    loadingDialog2.dismiss();
                }
            }

            @Override
            public void onError(String errorMsg) {
                if (loadingDialog2 != null) {
                    loadingDialog2.dismiss();
                }
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class TypeAdapter extends BaseQuickAdapter<KnowledgeTypeEntity, BaseViewHolderEx> {
        private Context context;

        public TypeAdapter(int layoutResId, Context context, @Nullable List<KnowledgeTypeEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, KnowledgeTypeEntity item) {
            ImageView ivStatus = helper.getView(R.id.ivStatus);
            TextView tvTiltle = helper.getView(R.id.tvTiltle);
            tvTiltle.setText(item.getName());
            if (item.isSelect()) {
                ivStatus.setSelected(true);
            } else {
                ivStatus.setSelected(false);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.isSelect()) {
                        typeEntityList.get(helper.getItemPosition()).setSelect(false);
                        typeEntityList.get(0).setSelect(false);
                    } else {
                        typeEntityList.get(helper.getItemPosition()).setSelect(true);
                        if (helper.getItemPosition() > 0) {
                            if (typeEntityList.get(1).isSelect() && typeEntityList.get(2).isSelect() && typeEntityList.get(3).isSelect()&& typeEntityList.get(4).isSelect()&& typeEntityList.get(5).isSelect()) {
                                typeEntityList.get(0).setSelect(true);
                            } else {
                                typeEntityList.get(0).setSelect(false);
                            }
                        } else {
                            typeEntityList.get(1).setSelect(true);
                            typeEntityList.get(2).setSelect(true);
                            typeEntityList.get(3).setSelect(true);
                            typeEntityList.get(4).setSelect(true);
                            typeEntityList.get(5).setSelect(true);
                        }
                    }
                    typeAdapter.notifyDataSetChanged();
                    if (loadingDialog2 != null) {
                        loadingDialog2.show();
                    }
                    getCatalogData();
                    getLatelyResourceList();
                    rlType.setVisibility(View.GONE);
                    ivRight.setBackgroundResource(R.drawable.arrow_down_all);
                }
            });
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            HashMap<String, String> map = messageEvent.getHashMap();
            if(map.containsKey("DocumentPreview_error")){
                for (int i = 0; i < justList.size(); i++) {
                    if ("1".equals(justList.get(i).getResourceType())) {
                        if (justList.get(i).getResourceId().equals(map.get("DocumentPreview_error"))) {
                            justList.get(i).setError(true);
                        }
                    }
                }
            }
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                for (int i = 0; i < justList.size(); i++) {
                    if ("1".equals(justList.get(i).getResourceType())) {
                        if (justList.get(i).getResourceId().equals(recevierDataCode)) {
                            if (!justList.get(i).isOpen()) {
                                if(encryptStatus){
                                    justList.get(i).setOpen(true);
                                }
                                dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                            }

                        }
                    }
                }

            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                mContext.startActivity(newIntent);
            }
        } else {
            if (position < 0) {
                return;
            }
            if (percent > 0 && percent < 100) {
                if (justOpenListAdapter != null) {
                    justList.get(position).setProgress(percent);
                    justOpenListAdapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (justOpenListAdapter != null) {
                    justList.get(position).setProgress(100);
                    justOpenListAdapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(mContext, fileUrl, fileName, recevierDataCode, TAG);
                        }
                    }.start();
                }


            }else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(TAG);// 获取数据
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @OnClick({R.id.title_back, R.id.llRight, R.id.rlType})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                if (mContext != null) {
                    mContext.finish();
                }
                break;
            case R.id.llRight:
                if (rlType.getVisibility() == View.VISIBLE) {
                    rlType.setVisibility(View.GONE);
                    ivRight.setBackgroundResource(R.drawable.arrow_down_all);
                } else {
                    rlType.setVisibility(View.VISIBLE);
                    ivRight.setBackgroundResource(R.drawable.arrow_up_all);
                }
                break;
            case R.id.rlType:
                rlType.setVisibility(View.GONE);
                ivRight.setBackgroundResource(R.drawable.arrow_down_all);
                break;
        }

    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && mContext != null) {
            LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
        }
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(getActivity())
                .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.grey_3)  /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
    }
}
